<template>
	<view class="result-list-container">
		<!-- 组别Tab -->
		<view class="tab-container">
			<scroll-view class="result-tabs" :scroll-x="true" @scroll="onGroupScroll" :scroll-left="groupScrollLeft">
				<block v-for="(tab, idx) in groupTabs" :key="idx">
					<view :class="['tab', { active: activeGroup === idx }]" @click="getGroupList(tab, idx)">
						{{ tab.group_name }}
					</view>
				</block>
			</scroll-view>
			<view v-if="showGroupScrollIndicator" class="scroll-indicator">
				<view class="scroll-bar">
					<view class="scroll-dot"></view>
					<view class="scroll-dot"></view>
					<view class="scroll-dot"></view>
				</view>
			</view>
		</view>

		<!-- 项目Tab -->
		<view class="tab-container">
			<scroll-view class="result-tabs sub-tabs" scroll-x @scroll="onEventScroll" :scroll-left="eventScrollLeft">
				<view v-for="(tab, idx) in eventTabs" :key="tab" :class="['tab', { active: activeEvent === idx }]"
					@click="getEventList(tab, idx)">
					{{ tab.item_name }}
				</view>
			</scroll-view>
			<view v-if="showEventScrollIndicator" class="scroll-indicator">
				<view class="scroll-bar">
					<view class="scroll-dot"></view>
					<view class="scroll-dot"></view>
					<view class="scroll-dot"></view>
				</view>
			</view>
		</view>

		<!-- 轮次Tab -->
		<scroll-view class="result-tabs sub-tabs" scroll-x>
			<view v-for="(tab, idx) in roundTabs" :key="tab" :class="['tab', { active: activeRound === idx }]"
				@click="getRoundList(tab, idx)">
				{{ tab.name }}
			</view>
		</scroll-view>
		<!-- 成绩列表 -->
		<view class="result-list">
			<view v-for="(item, idx) in resultData" :key="idx" class="result-item">
				<view class="rank">
					<image v-if="item.rank <= 3" class="medal" :src="getMedalIcon(item.rank)" />
					<text v-else class="rank-num">{{ item.rank }}</text>
					<!-- <image v-if="idx === 0" :src="imgUrl + 'firstPlace.png'" class="medal" />
          <image v-else-if="idx === 1" :src="imgUrl + 'runner-up.png'" class="medal" />
          <image v-else-if="idx === 2" :src="imgUrl + 'thirdPlace.png'" class="medal" />
          <text v-else>{{ idx + 1 }}</text> -->
				</view>
				<image :src="item.avatar ? item.avatar : imgUrl + 'avatar1@2x.png'" class="avatar" />
				<view class="name-info">
					<view class="name-row">
						<view class="name">{{ item.username }}</view>
						<text v-if="item.islate" class="late-tag">迟到</text>
					</view>
					<view class="number">{{ item.num }}</view>
				</view>
				<view class="time">{{ item.score }}</view>
				<view class="result">{{
          item.rank
            ? item.rank == 1
              ? '冠军'
              : item.rank == 2
                ? '亚军'
                : item.rank == 3
                  ? '季军'
                  : '--'
            : '--'
        }}</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch,
		nextTick
	} from 'vue'
	import {
		imgUrl
	} from '@/utils/config'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		useRequest
	} from '@/api'
	const props = defineProps({
		mainId: {
			type: Number,
			required: true
		},
		competition_time: {
			type: Number,
			required: true
		}
	})
	const {
		API_EVENT_ITEMS_POST,
		API_EVENT_GROUP_POST,
		API_INDEX_DETAIL_SCORE_POST,
		API_INDEX_LISTSCORE_POST
	} = useRequest()
	const activeGroup = ref(0)
	const activeEvent = ref(0)
	const activeRound = ref(0)
	const eventId = ref('') // 赛事id
	const itemId = ref('') // 项目id
	const groupId = ref('') // 组别id
	const stage = ref('heat') // 赛事阶段

	// 滚动相关状态
	const groupScrollLeft = ref(0)
	const eventScrollLeft = ref(0)
	const showGroupScrollIndicator = ref(false)
	const showEventScrollIndicator = ref(false)

	// 存储所有原始数据
	const allResultData = ref([])
	const resultData = ref([])

	// 存储所有Tab选项
	const allGroupTabs = ref([])
	const allEventTabs = ref([])
	const allRoundTabs = ref([])

	// 当前显示的Tab选项
	const groupTabs = ref([])
	const eventTabs = ref([])
	const roundTabs = ref([{
			stage: 'heat',
			name: '预赛'
		},
		{
			stage: 'finals',
			name: '决赛'
		}
	])

	function getMedalIcon(rank) {
		const icons = {
			1: imgUrl + 'firstPlace@2x.png',
			2: imgUrl + 'runner-up@2x.png',
			3: imgUrl + 'thirdPlace@2x.png'
		}
		return icons[rank]
	}

	// 滚动事件处理
	const onGroupScroll = (e) => {
		const { scrollLeft, scrollWidth } = e.detail
		groupScrollLeft.value = scrollLeft
		// 检查是否需要显示滚动指示器
		checkGroupScrollIndicator(scrollLeft, scrollWidth)
	}

	const onEventScroll = (e) => {
		const { scrollLeft, scrollWidth } = e.detail
		eventScrollLeft.value = scrollLeft
		// 检查是否需要显示滚动指示器
		checkEventScrollIndicator(scrollLeft, scrollWidth)
	}

	// 检查组别Tab是否需要显示滚动指示器
	const checkGroupScrollIndicator = (scrollLeft = 0, scrollWidth = 0) => {
		// 获取屏幕宽度
		uni.getSystemInfo({
			success: (res) => {
				const screenWidth = res.windowWidth
				console.log('组别Tab检测:', { scrollLeft, scrollWidth, screenWidth, tabCount: groupTabs.value.length })
				
				// 如果Tab数量少于等于4个，不显示指示器
				if (groupTabs.value.length <= 4) {
					showGroupScrollIndicator.value = false
					console.log('组别Tab应该显示指示器: false (Tab数量不足)')
					return
				}
				
				// 如果scrollWidth为0（初始化时），使用Tab数量估算
				if (scrollWidth === 0) {
					// 估算每个Tab的宽度（包括padding和margin）
					const estimatedTabWidth = 120 // 大约120rpx per tab
					const estimatedTotalWidth = groupTabs.value.length * estimatedTabWidth
					const shouldShow = estimatedTotalWidth > screenWidth
					console.log('组别Tab应该显示指示器 (估算):', shouldShow, '估算总宽度:', estimatedTotalWidth)
					showGroupScrollIndicator.value = shouldShow
					return
				}
				
				// 如果内容宽度大于屏幕宽度，且当前滚动位置不是最右边，则显示指示器
				const shouldShow = scrollWidth > screenWidth && scrollLeft < scrollWidth - screenWidth + 20
				console.log('组别Tab应该显示指示器:', shouldShow, '滚动位置:', scrollLeft, '总宽度:', scrollWidth, '屏幕宽度:', screenWidth)
				showGroupScrollIndicator.value = shouldShow
			}
		})
	}

	// 检查项目Tab是否需要显示滚动指示器
	const checkEventScrollIndicator = (scrollLeft = 0, scrollWidth = 0) => {
		// 获取屏幕宽度
		uni.getSystemInfo({
			success: (res) => {
				const screenWidth = res.windowWidth
				console.log('项目Tab检测:', { scrollLeft, scrollWidth, screenWidth, tabCount: eventTabs.value.length })
				
				// 如果Tab数量少于等于3个，不显示指示器
				if (eventTabs.value.length <= 3) {
					showEventScrollIndicator.value = false
					console.log('项目Tab应该显示指示器: false (Tab数量不足)')
					return
				}
				
				// 如果scrollWidth为0（初始化时），使用Tab数量估算
				if (scrollWidth === 0) {
					// 估算每个Tab的宽度（项目Tab通常更长）
					const estimatedTabWidth = 200 // 大约200rpx per tab
					const estimatedTotalWidth = eventTabs.value.length * estimatedTabWidth
					const shouldShow = estimatedTotalWidth > screenWidth
					console.log('项目Tab应该显示指示器 (估算):', shouldShow, '估算总宽度:', estimatedTotalWidth)
					showEventScrollIndicator.value = shouldShow
					return
				}
				
				// 如果内容宽度大于屏幕宽度，且当前滚动位置不是最右边，则显示指示器
				const shouldShow = scrollWidth > screenWidth && scrollLeft < scrollWidth - screenWidth + 20
				console.log('项目Tab应该显示指示器:', shouldShow, '滚动位置:', scrollLeft, '总宽度:', scrollWidth, '屏幕宽度:', screenWidth)
				showEventScrollIndicator.value = shouldShow
			}
		})
	}
	// 前端筛选数据
	const filterResultData = () => {
		if (!allResultData.value || allResultData.value.length === 0) {
			resultData.value = []
			return
		}

		let filteredData = [...allResultData.value]

		// 根据当前选中的条件筛选
		if (activeEvent.value >= 0 && allEventTabs.value[activeEvent.value]) {
			const currentEvent = allEventTabs.value[activeEvent.value]
			filteredData = filteredData.filter(item => item.item_id === currentEvent.item_id)
		}

		if (activeGroup.value >= 0 && groupTabs.value[activeGroup.value]) {
			const currentGroup = groupTabs.value[activeGroup.value]
			filteredData = filteredData.filter(item => item.group_id === currentGroup.group_id)
		}

		if (activeRound.value >= 0 && roundTabs.value[activeRound.value]) {
			const currentRound = roundTabs.value[activeRound.value]
			filteredData = filteredData.filter(item => item.stage === currentRound.stage)
		}

		resultData.value = filteredData
		console.log('筛选后的数据:', resultData.value)
	}

	const getGroupList = async (tab, idx) => {
		activeGroup.value = idx
		groupId.value = tab.group_id
		// 前端筛选，不重新请求
		// filterResultData()
		await getEventItems(tab.group_id)
		await getAllDetailScore()
	}

	const getEventList = async (tab, idx) => {
		itemId.value = tab.item_id
		activeEvent.value = idx
		await getAllDetailScore()
		// // 更新组别Tab选项
		// updateGroupTabs()

		// // 前端筛选，不重新请求
		// filterResultData()
	}

	const getRoundList = async (tab, idx) => {
		activeRound.value = idx
		stage.value = tab.stage
		await getAllDetailScore()
		// 前端筛选，不重新请求
		// filterResultData()
	}

	// 更新组别Tab选项
	const updateGroupTabs = () => {
		if (!allResultData.value || allResultData.value.length === 0) {
			groupTabs.value = []
			return
		}

		const currentEvent = allEventTabs.value[activeEvent.value]
		if (!currentEvent) {
			groupTabs.value = []
			return
		}

		// 从当前项目的数据中提取组别信息
		const groups = allResultData.value
			.filter(item => item.item_id === currentEvent.item_id)
			.map(item => ({
				group_id: item.group_id,
				group_name: item.group_name
			}))
			.filter((group, index, self) =>
				index === self.findIndex(g => g.group_id === group.group_id)
			)

		groupTabs.value = groups

		// 如果当前选中的组别不在新的组别列表中，重置为第一个
		if (groupTabs.value.length > 0 &&
			!groupTabs.value.find(g => g.group_id === groupId.value)) {
			activeGroup.value = 0
			groupId.value = groupTabs.value[0].group_id
		}
	}

	const getEventItems = async (group_id) => {
		let params = {
			event_id: eventId.value,
			group_id,
			page: 1,
			page_size: 1000,
		}
		// allEventTabs.value = []
		// itemId.value = ''
		eventTabs.value = []
		try {
			const res = await API_EVENT_ITEMS_POST(params)

			if (res.code === 1) {
				// if (res.data.data.length > 0) {
				//   allEventTabs.value = res.data.data
				//   eventTabs.value = [...allEventTabs.value] // 复制一份用于显示
				//   if (allEventTabs.value.length > 0) {
				//     itemId.value = allEventTabs.value[0].item_id
				//     updateGroupTabs() // 更新组别Tab
				//   }
				// } else {
				//   allEventTabs.value = []
				//   eventTabs.value = []
				// }

				eventTabs.value = res.data.data

				itemId.value = res.data.data[0].item_id // 项目id

				// 等待DOM更新后检查滚动指示器
				await nextTick()
				setTimeout(() => {
					// 初始化时直接基于Tab数量检测
					checkEventScrollIndicator(0, 0)
				}, 100)

			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}

	const getEventGroup = async () => {
		let params = {
			page: 1,
			page_size: 1000,
			event_id: eventId.value,
			// item_id: itemId.value
		}
		// allGroupTabs.value = [] // 存储所有原始组别
		try {
			const res = await API_EVENT_GROUP_POST(params)
			console.log('getEventGroup', res)

			if (res.code === 1) {
				// groupTabs.value = res.data.data
				let data = res.data.data
				let uniqueByGroup = [...new Map(data.map(item => [item.group_id, item])).values()]
				groupTabs.value = uniqueByGroup
				console.log('uniqueByGroup', groupTabs.value);
				groupId.value = uniqueByGroup[0].group_id
				await getEventItems(uniqueByGroup[0].group_id)
				
				// 等待DOM更新后检查滚动指示器
				await nextTick()
				setTimeout(() => {
					// 初始化时直接基于Tab数量检测
					checkGroupScrollIndicator(0, 0)
				}, 100)
				// if (res.data.data.length > 0) {
				//   allGroupTabs.value = res.data.data
				//   console.log('allGroupTabs', allGroupTabs.value)

				//   if (allGroupTabs.value.length > 0) {
				//     groupId.value = allGroupTabs.value[0].group_id
				//     updateGroupTabs() // 更新组别Tab选项
				//   }
				// } else {
				//   allGroupTabs.value = []
				//   groupId.value = ''
				// }

			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}

	// 获取所有成绩数据（只调用一次）
	const getAllDetailScore = async () => {
		let params = {
			id: eventId.value,
			item_id: itemId.value,
			group_id: groupId.value,
			stage: stage.value
			// 不传具体的筛选条件，获取所有数据
		}
		try {
			const res = await API_INDEX_LISTSCORE_POST(params)
			if (res.code == 1) {
				console.log('getAllDetailScore', res)

				// if (res.data.data.length > 0) {
				//   allResultData.value = res.data.data
				//   filterResultData() // 筛选数据
				// } else {
				//   allResultData.value = []
				//   resultData.value = []
				// }
				resultData.value = res.data.data
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}
	// 监听 mainId 数据变化
	watch(
		() => props.mainId,
		async (newMainId) => {
			if (newMainId && newMainId > 0) {
				eventId.value = newMainId
				// 在这里处理数据更新后的逻辑 
				await getEventGroup() //获取组别
				// await getEventItems() //赛事下所有项目

				await getAllDetailScore() // 获取所有成绩数据
				// 等待 DOM 更新完成
				await nextTick()
				// filterResultData() // 筛选数据
			}
		}, {
			immediate: true,
			deep: true
		}
	)
	// watch(() => activeGroup.value, async (newActiveGroup) => {
	//   console.log('activeGroup data updated:', newActiveGroup);
	// }, { immediate: true, deep: true });
	// watch(() => activeEvent.value, async (newActiveEvent) => {
	//   console.log('activeEvent data updated:', newActiveEvent);
	// }, { immediate: true, deep: true });
	// watch(() => activeRound.value, async (newActiveRound) => {
	//   console.log('activeRound data updated:', newActiveRound);
	// }, { immediate: true, deep: true });
</script>

<style lang="scss" scoped>
	.tab-container {
		position: relative;
		margin-bottom: 24rpx;
	}

	.result-tabs {
		white-space: nowrap;
		width: 100%;

		.tab {
			padding: 12rpx 32rpx;
			box-sizing: border-box;
			font-size: 24rpx;
			color: #888;
			background: #f5f5f5;
			border-radius: 12rpx;
			margin-right: 16rpx;
			font-weight: 500;
			display: inline-block;

			&.active {
				background: #213165;
				color: #fff;
			}
		}

		&.sub-tabs {
			.tab {
				font-size: 26rpx;
				padding: 10rpx 24rpx;
			}
		}
	}

	.scroll-indicator {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.9));
		padding: 12rpx 16rpx 12rpx 40rpx;
		pointer-events: none;
		z-index: 10;

		.scroll-bar {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 4rpx;

			.scroll-dot {
				width: 6rpx;
				height: 6rpx;
				background: #999;
				border-radius: 50%;
				opacity: 0.6;
				animation: scroll-dot-pulse 1.5s infinite ease-in-out;

				&:nth-child(2) {
					animation-delay: 0.2s;
				}

				&:nth-child(3) {
					animation-delay: 0.4s;
				}
			}
		}
	}

	@keyframes scroll-dot-pulse {
		0%, 100% {
			opacity: 0.3;
			transform: scale(0.8);
		}
		50% {
			opacity: 0.8;
			transform: scale(1.2);
		}
	}

	.result-list {
		.result-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			.rank {
				width: 48rpx;
				text-align: center;
				font-size: 30rpx;
				color: #666;
				margin-right: 16rpx;

				.medal {
					width: 36rpx;
					height: 36rpx;
				}
			}

			.avatar {
				width: 36rpx;
				height: 48rpx;
				border-radius: 50%;
				margin-right: 16rpx;
			}

			.name-info {
				flex: 1.5;

				.name-row {
					display: flex;
					align-items: center;
					gap: 8rpx;
				}

				.name {
					font-size: 28rpx;
					color: #333;
				}

				.late-tag {
					font-size: 20rpx;
					color: #ff4444;
					background: #ffe6e6;
					padding: 2rpx 8rpx;
					border-radius: 4rpx;
					font-weight: 500;
				}

				.number {
					font-size: 24rpx;
					color: #999;
				}
			}

			.time {
				flex: 1;
				font-size: 26rpx;
				color: #333;
				text-align: center;
			}

			.result {
				flex: 1;
				font-size: 26rpx;
				color: #333;
				text-align: right;
				/* font-weight: bold; */
			}
		}
	}
</style>